package com.niit.serviceuser.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
import com.niit.common.entity.TbUser;
import com.niit.serviceuser.service.OrderFeignClient;
import com.niit.serviceuser.service.TbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/users")
public class TbUserController {

    @Autowired // 依赖注入
    RestTemplate restTemplate;

    @Autowired
    private TbUserService tbUserService;

    @Autowired
    OrderFeignClient orderFeignClient;

    @GetMapping
    public List<TbUser> getAllUsers() {
        return tbUserService.getAllUsers();
    }

    @GetMapping("/{id}")
    public TbUser getUserById(@PathVariable Long id) {
        return tbUserService.getUserById(id);
    }

    @PostMapping
    public int createUser(@RequestBody TbUser user) {
        return tbUserService.createUser(user);
    }

    @PutMapping("/{id}")
    public int updateUser(@PathVariable Long id, @RequestBody TbUser user) {
        return tbUserService.updateUser(user);
    }

    @DeleteMapping("/{id}")
    public int deleteUser(@PathVariable Long id) {
        return tbUserService.deleteUser(id);
    }

    // 调用service-order服务查询所有订单信息
    @GetMapping("/orders")
    @HystrixCommand(fallbackMethod = "getAllOrdersFallback",ignoreExceptions = {RuntimeException.class, Exception.class})
    @CacheResult
    public List<TbUser> getAllOrders() {

        String url="http://service-order/orders";
        return restTemplate.getForObject(url, List.class);

    }
    // 服务降级方法的实现
    public List<TbUser> getAllOrdersFallback(){
        System.out.println("服务降级的HystrixCommand的实现");
        return new ArrayList<TbUser>();
    }

    @GetMapping("/port")
    public String getPort() {
        // 服务降级时候 可以执行
        return  orderFeignClient.getPort();
    }
}